import { reqCartList, reqAddShopCart, reqChangeChecked, reqDeleteOneCart, reqChangeAllChecked } from '@/api/index'
const state = {
  cartList: []
}
const mutations = {
  RECEIVE_CARTLIST (state, cartList) {
    state.cartList = cartList
  }
}
const actions = {
  //获取购物车列表
  async getCartList ({ commit }, userId) {
    const cartListData = await reqCartList(userId)
    if (cartListData.code === 200) {
      commit('RECEIVE_CARTLIST', cartListData.data)
    }
  },
  //添加购物车
  async addOrUpdateShopCart ({ commit }, { productId, productNum }) {
    const result = await reqAddShopCart(productId, productNum)
    if (result.code === 200) {
      return 'OK'
    } else {
      return Promise.reject(new Error('添加购物车failed'))
    }
  },
  //修改商品选中状态
  async changeChecked ({ commit }, { productId, checked }) {
    const result = await reqChangeChecked(productId, checked)
    if (result.code === 200) {
      return 'OK'
    } else {
      return Promise.reject(new Error('修改购物车failed'))
    }
  },
  //删除单个购物车商品
  async deleteOneCart ({ commit }, productId) {
    const result = await reqDeleteOneCart(productId)
    console.log(result)
    if (result.code === 200) {
      return 'OK'
    } else {
      return Promise.reject(new Error('删除单个购物车failed'))
    }
  },
  //修改全选/全不选
  async changeAllChecked ({ commit }, checked) {
    const result = await reqChangeAllChecked(checked)
    if (result.code === 200) {
      return 'OK'
    } else {
      return Promise.reject(new Error('全选全不选状态修改failed'))
    }
  }
}
const getters = {
  allMoney (state) {
    return state.cartList.reduce((prev, item) => {
      if (item.checked) {
        prev += item.productNum * item.salePrice
      }
      return prev
    }, 0)
  },
  //共有几件商品
  allNum (state) {
    return state.cartList.reduce((prev, item) => {
      return prev += item.productNum * 1
    }, 0)
  },
  //选中几件
  allCheckNum (state) {
    return state.cartList.reduce((prev, item) => {
      if (item.checked == 1) {
        prev += item.productNum * 1
      }
      return prev
    }, 0)
  }
}
export default {
  state,
  mutations,
  actions,
  getters
}
